package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @projectName: BlogUIAutoTest
 * @package: common
 * @className: Util
 * @author: Tongxinxin
 * @description: TODO
 * @date: 2025/9/4 14:35
 * @version: 1.0
 */
public class Util {
    public WebDriver driver=null;
    /**
    * 创建驱动对象
    * */
    public WebDriver createDriver(){
        if(driver==null){
            //设置本地Edge驱动路径
            System.setProperty("webdriver.edge.driver","D:\\Java\\Maven\\.m2\\edgedriver_win64\\msedgedriver.exe");
            EdgeOptions options = new EdgeOptions();
            //添加配置：允许访问所有连接
            options.addArguments("--remote-allow-origins=*");
            //创建驱动对象
            driver=new EdgeDriver(options);
            //设隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }
//    /**
//     * 获取网页URL
//     */
//    public void Utils(String url){
//        driver=createDriver();
//        driver.get(url);
//    }

    /**
     * 设置屏幕截图
     * */
    public void Screenshot(String str) throws IOException {
        //年月日
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        //时分秒
        SimpleDateFormat sim2 = new SimpleDateFormat("HH-mm-ss");
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        //图片文件名：路径+文件名称
        //BlogUIAutoTest/src/test/java/image/2025-09-04/test01-15-14-22.png
        String filename = "BlogUIAutoTest/src/test/java/image/" + dirTime + "/" + str + "-" + fileTime + ".png";
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile, new File(filename));
    }
    /**
     * 销毁driver对象——关闭浏览器
     */
    public void quit() {
        if(driver!=null){
            driver.quit();
        }
    }
}
